package com.testing.Utlis;

import org.ini4j.Wini;

import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

public class IniUtils {
    public IniUtils() {
    }

    public static final String INIFILEPATH = "src/main/resources/config/element.ini";

    /**
     * 读取ini文件信息
     * @param urlPath ini文件位置
     * @return 读取ini文件以map返回
     */
    public static Map<String,String> readIniFile(String urlPath){
        InputStream in = null;
        try {
            in = new FileInputStream(new File(urlPath));

            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            Properties props = new Properties();
            props.load(br);
            Map<String, String> map = new HashMap<>();
            for(Object s: props.keySet()){
                map.put(s.toString(), props.getProperty(s.toString()));
            }
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 写入ini文件数据
     *
     * @param urlPath ini文件位置
     * @param title   头信息（详细见ini文件格式）
     * @param map     写入的数据
     */
    public static void writeIniFile(String urlPath, String title, LinkedHashMap<String,Object> map){
        Wini wini = null;
        try {
            wini = new Wini(new File(urlPath));

            for (Map.Entry<String, Object> next : map.entrySet()) {
                wini.put(title, next.getKey(), next.getValue());
            }
            wini.store();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


